import axios, { AxiosRequestConfig } from "axios";
import { BASE_URL } from "./config";
import { Notify, Toast } from "react-vant";
import { MyResponseType } from "../types";
import { store } from "../store";

const service = axios.create({
  baseURL: BASE_URL,
});

// http request 拦截器
service.interceptors.request.use(
  (config) => {
    const state = store.getState();
    // 发送网络请求时, 在界面的中间位置显示Loading的组件,使用react-vant插件，这里不再赘述
    Toast.loading({
      message: "加载中",
      forbidClick: true,
      loadingType: "ball",
    });
    //请求公共参数携带的信息

    config.headers.sessionId = state.user.doctor.sessionId;
    config.headers.doctorId = state.user.doctor.doctorId;

    return config;
  },
  (err) => {
    Toast.clear();
    //...关闭加载loading的组件，显示消息提示弹窗
    return Promise.reject(err);
  }
);

// http response 拦截器
service.interceptors.response.use(
  (res) => {
    Toast.clear();
    const { status, message } = res.data;
    switch (status) {
      case "9999":
        break;
      case "9001":
        console.log("服务端错误");
        break;
      case "8001":
        console.log("用户业务错误");
        Notify.show({ type: "danger", message });
        break;
      case "8002":
        console.log("医生业务错误");
        break;
      case "8003":
        console.log("公共业务错误");
        break;
    }
    return res;
  },
  (err) => {
    Toast.clear();
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          console.log("请求错误");
          break;
        case 401:
          console.log("未授权访问");
          break;
        case 404:
          console.log("资源找不到");
          break;
        default:
          console.log("其他错误信息");
      }
    }
    return Promise.reject(err);
  }
);

const request = async <T = any>(
  config: AxiosRequestConfig
): Promise<MyResponseType<T>> => {
  try {
    const resp = await service.request<MyResponseType<T>>(config);
    return resp.data;
  } catch (err: any) {
    const message = err.message || "请求失败";
    console.error(message); // 失败消息提示
    return {
      status: "4000",
      message,
      result: null as any,
    };
  }
};

export default request;
